package com.ambitor.ipro.service;

import java.sql.Connection;
import java.util.Date;

import com.ambitor.grass.sql.dao.BaseDao;
import com.ambitor.grass.sql.data.Parameter;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.SkyenccUtil;
import com.ambitor.ipro.util.TableName;

public class UnInstallService extends BaseService {

	private TopService topService = null;

	public UnInstallService(Connection conn) {
		super(conn);
		topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IMPROMOTION, Constants.APP_SECRET_IMPROMOTION);
	}

	@SuppressWarnings("unchecked")
	public IDataset getProSettingWithUserId(String userId) throws Exception {
		String sql = "select * from "
				+ TableName.TF_P_USER_PRO
				+ " where user_id = ? and valid_flag in(1,2) and web_install_flag = 1";
		Parameter param = new Parameter();
		param.add(userId);
		return superDao.queryListBySql(sql, param);
	}

	@SuppressWarnings("unchecked")
	public void uninstallDBSetting(IDataset proSettingList) throws Exception {
		IDataset updateParamList = new DatasetList();
		String now = SkyenccUtil.formatDate(new Date());
		for (int i = 0; i < proSettingList.count(); i++) {
			IData updateParam = new DataMap();
			updateParam.put("PRO_ID", proSettingList.get(i, "PRO_ID"));
			updateParam.put("VALID_FLAG", Constants.FLAG_NO);
			updateParam.put("END_TIME", now);
			updateParamList.add(updateParam);
		}
		superDao.update(TableName.TF_P_USER_PRO, updateParamList);
	}

	public void uninstallFromTaobaoItem(String sessionId, String nick,
			IDataset proSettingList) throws Exception {
		for (int i = 0; i < proSettingList.count(); i++) {
			String str = (String) proSettingList.get(i, "INSTALL_IID");
			topService.uninstallPromotionModule(sessionId, nick, Long
					.decode(str), "all");
		}
	}

	public void unstallDeamon(String userId) {
		String sql = "select * from "
				+ TableName.TF_P_USER_PRO
				+ " where user_id = ? and valid_flag in(1,2) and web_install_flag = 1";
		Parameter param = null;
		try {
			param = new Parameter();
			param.add(userId);
			IDataset dataset = superDao.queryListBySql(sql, param);
			for (int i = 0; i < dataset.size(); i++) {
				IData data = dataset.getData(i);
				superDao.save("tt_p_uninstall", data);
			}

			sql = "update " + TableName.TF_P_USER_PRO
					+ " set valid_flag ='0' where user_id = ?";
			BaseDao baseDao = superDao.getBaseDao();
			baseDao.executeUpdate(sql, param);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
